
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_swipe_action_cell/core/cell.dart';
import 'package:get/get.dart';
import 'package:smart_freezer/core/model/share_model.dart';
import 'package:smart_freezer/core/resources/app_config.dart';
import 'package:smart_freezer/core/resources/icon_names.dart';
import 'package:smart_freezer/core/service/api/app_api.dart';
import 'package:smart_freezer/core/service/service/net_service.dart';
import 'package:smart_freezer/core/utils/local_storage.dart';
import 'package:smart_freezer/core/utils/tr_extension.dart';

import '../../../../generated/locale_keys.g.dart';

class DeviceShareList extends StatefulWidget {
  const DeviceShareList({Key? key}) : super(key: key);

  @override
  _DeviceShareListState createState() => _DeviceShareListState();
}

class _DeviceShareListState extends State<DeviceShareList> {

  List<ShareModel> _shareList = [];
  int currentPage = 1;

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // backgroundColor: Colors.white,
        elevation: 0,
        leadingWidth: 50,
        leading: InkWell(
          onTap: () {
            Get.back();
          },
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 9, 0, 9),
            child: Icon(Icons.arrow_back_ios_rounded),
          ),
        ),
        title: Text(LocaleKeys.device_info_share_people.trc(),),
        centerTitle: true,
      ),
      body: Container(
        width: MainCommon.screenWidth,
        child: Column(
          children: [
            // Container(
            //   color: Colors.white,
            //   width: MainCommon.screenWidth,
            //   height: 0,
            //   child: Text(LocaleKeys.device_info_shared.trc(), style: TextStyle(color: Colors.grey),),
            //   alignment: Alignment.centerLeft,
            //   padding: EdgeInsets.only(left: 10),
            // ),
            Divider(
              height: 1,
              indent: 5,
              endIndent: 5,
            ),

            Expanded(
              child: EasyRefresh.custom(
                header: MaterialHeader(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                footer: MaterialFooter(valueColor: AlwaysStoppedAnimation(isDarkMode ? Colors.white : Colors.black)),
                firstRefresh: true,
                emptyWidget: _shareList.isEmpty ? Center(
                  child: Column(
                    children: [
                      SizedBox(height: 50,),
                      Image.asset(IconNames.home_w06, width: MainCommon.screenWidth * 0.6,),
                      Text(LocaleKeys.other_no_data.trc(), style: TextStyle(color: Colors.grey),),
                    ],
                  ),
                ) : null,
                slivers: [
                  SliverList(
                  delegate: SliverChildBuilderDelegate(
                      (context, index) {
                        final model = _shareList[index];

                        return SwipeActionCell(
                          key: ObjectKey(model),
                          index: index,
                          trailingActions: <SwipeAction>[
                            SwipeAction(
                              widthSpace: 50,
                              content: Container(
                                width: 50,
                                decoration: BoxDecoration(
                                  gradient: LinearGradient(
                                    colors: [Color(0xFFF42850), Color(0xFFEB39B1),],
                                    begin: Alignment.centerRight,
                                    end: Alignment.centerLeft,
                                  )
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(Icons.delete_forever, color: Colors.white, size: 19,),
                                    Text(LocaleKeys.device_info_delete.trc(), style: TextStyle(color: Colors.white, fontSize: 12),),
                                  ],
                                ),
                              ),
                              onTap: (CompletionHandler handler) async {
                                final model = _shareList[index];
                                _deleteShareList(model.id);
                              },
                            ),

                            SwipeAction(
                              widthSpace: 0,   // 暂时隐藏, 不可编辑权限
                              content: Container(
                                width: 50,
                                decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      colors: [Color(0xFF175CE5), Color(0xFF41C4DE),],
                                      begin: Alignment.centerRight,
                                      end: Alignment.centerLeft,
                                    )
                                ),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.center,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    Icon(Icons.edit_road, color: Colors.white, size: 19,),
                                    Text(LocaleKeys.device_info_edit.trc(), style: TextStyle(color: Colors.white, fontSize: 12),),
                                  ],
                                ),
                              ),
                              onTap: (CompletionHandler handler) async {
                                final model = _shareList[index];
                                // 先获取当前分享信息
                                _getShareDetail(model.id);
                              },
                            ),
                          ],
                          child: Container(
                            color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
                            height: 50,
                            padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
                            child: Column(
                              children: [
                                Container(
                                  height: 49,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        children: [
                                          Container(
                                            decoration: BoxDecoration(
                                              color: Colors.grey.shade200,
                                              borderRadius: BorderRadius.circular(15)
                                            ),
                                            width: 30,
                                            height: 30,
                                          ),
                                          SizedBox(width: 10,),
                                          Column(
                                            mainAxisAlignment: MainAxisAlignment.center,
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Text(model.invitedCustomerName, style: TextStyle(fontSize: 15),),
                                              Text(model.shareTime, style: TextStyle(fontSize: 13, color: Colors.grey),)
                                            ],
                                          ),

                                        ],
                                      ),


                                      Padding(
                                        padding: EdgeInsets.only(right: 10),
                                        child: Icon(Icons.chevron_right, color: Colors.grey.shade400,),
                                      ),
                                    ],
                                  ),
                                ),
                                Divider(
                                  height: 1,
                                  indent: 5,
                                  endIndent: 0,
                                ),
                              ],
                            ),
                          ),
                        );
                      },
                      childCount: _shareList.length
                  )
                  )
                ],
                onRefresh: () async {
                  _getNewList();
                },
                onLoad: () async {
                  _getMoreList();
                },
              ),
            )
          ],
        ),
      ),
    );
  }

  _getNewList() {
    _shareList = [];
    currentPage = 1;
    _getShareList(currentPage);
  }

  _getMoreList() {
    currentPage += 1;
    _getShareList(currentPage);
  }

  // 获取设备数据
  _getShareList(int page) async {
    final params = {"page": "${page}", "limit": "100"};
    ResultData data = await AppApi.getInstance().getShareList(params);
    if(data.code == 0){
      final list = data.data as List;
      if(list.isNotEmpty) {
        final modelList = list.map((e) => ShareModel.fromJson(e)).toList();
        _shareList.addAll(modelList);
      }
      setState(() {});
    } else {
      SmartDialog.showToast(data.msg);
    }
  }

  /// 获取分享详情
  _getShareDetail(String id) async {
    final params = {"page": "1", "limit": "100"};
    ResultData data = await AppApi.getInstance().getShareList(params);
    if(data.code == 0) {
      final list = data.data as List;
      if(list.isNotEmpty) {
        final modelList = list.map((e) => ShareModel.fromJson(e)).toList();
        final shareModel = modelList.firstWhere((element) => element.id == id);

        // 弹出编辑框
        showModalBottomSheet(
            context: context,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            builder: (_) {
              return PermissionWidget(permission: shareModel.permission, confirmTap: (selectValue) {
                _editShareList(id, selectValue.toString());
              },);
            }
        );
      }

    } else {
      SmartDialog.showToast(data.msg);
    }
  }

  /// 删除分享
  _deleteShareList(String id) async {
    final params = {"shareId": id,};
    ResultData data = await AppApi.getInstance().deleteShareInfo(params);
    if(data.code == 0){
      _getNewList();
    } else {
      SmartDialog.showToast(data.msg);
    }
  }

  /// 编辑分享
  _editShareList(String id, String permissionValue) async {
    final params = {"id": id, "permission": permissionValue};
    ResultData data = await AppApi.getInstance().updateShareInfo(params);
    if(data.code == 0){
      _getNewList();
    } else {
      SmartDialog.showToast(data.msg);
    }
  }

}

class PermissionWidget extends StatefulWidget {
  PermissionWidget({
    Key? key,
    this.permission = 0,
    required this.confirmTap,
  }) : super(key: key);

  // 默认无权限, 1可查看, 2可控制
  int permission = 0;
  // 确认
  ValueChanged confirmTap;

  @override
  _PermissionWidgetState createState() => _PermissionWidgetState();
}

class _PermissionWidgetState extends State<PermissionWidget> {

  int currentValue = 0;

  bool isDarkMode = LocalStorage.getThemeMode() == 1;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    currentValue = widget.permission;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 250,
      decoration: BoxDecoration(
        color: isDarkMode ? MainCommon.darkBlueMaterialColor : Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        ),
      ),
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.all(20.0),
            child: Text(LocaleKeys.device_info_share_permission.trc(), style: TextStyle(fontWeight: FontWeight.bold),),
          ),

          Column(
            children: [
              Container(
                width: MainCommon.screenWidth * 0.8,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: MainCommon.screenWidth * 0.7,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(LocaleKeys.device_info_ok_control.trc(), style: TextStyle(fontWeight: FontWeight.bold),),
                          Text(LocaleKeys.device_info_control_ok.trc(), style: TextStyle(color: Colors.grey),),
                        ],
                      ),
                    ),

                    InkWell(
                      onTap: (){
                        setState(() {
                          currentValue = 2;
                        });
                      },
                       child: Image.asset(currentValue == 2 ? IconNames.share_choose_selected : IconNames.share_choose_unselected, width: 30,)
                    ),
                  ],
                ),
              ),

              SizedBox(height: 20,),
              Container(
                width: MainCommon.screenWidth * 0.8,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Container(
                      width: MainCommon.screenWidth * 0.7,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(LocaleKeys.device_info_check.trc(), style: TextStyle(fontWeight: FontWeight.bold),),
                          Text(LocaleKeys.device_info_control_not_ok.trc(), style: TextStyle(color: Colors.grey),),
                        ],
                      ),
                    ),

                    InkWell(
                      onTap: () {
                        setState(() {
                          currentValue = 1;
                        });
                      },
                      child: Image.asset(currentValue == 1 ? IconNames.share_choose_selected : IconNames.share_choose_unselected, width: 30,)
                    ),
                  ],
                ),
              )
            ],
          ),

          Container(
            width: MainCommon.screenWidth,
            margin: EdgeInsets.only(top: 30),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                InkWell(
                  onTap: () {
                    Navigator.pop(context);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(LocaleKeys.login_cancel.trc(), style: TextStyle(fontWeight: FontWeight.bold, color: Colors.grey),),
                    height: 35,
                    width: 130,
                    decoration: BoxDecoration(
                      color: isDarkMode ? Colors.black : Color(0xFFF6F6F6),
                      borderRadius: BorderRadius.circular(15),
                    ),
                  ),
                ),

                InkWell(
                  onTap: () {
                    Navigator.pop(context);
                    widget.confirmTap(currentValue);
                  },
                  child: Container(
                    alignment: Alignment.center,
                    child: Text(LocaleKeys.add_device_confirm.trc(), style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF2EACC5)),),
                    height: 35,
                    width: 130,
                    decoration: BoxDecoration(
                      color: isDarkMode ? Colors.black : Color(0xFFF6F6F6),
                      borderRadius: BorderRadius.circular(15),
                    ),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

